<template>
  <div class="pf-flow-approval-info pf-bgwhite">
    <el-divider> 发单信息 </el-divider>
    <pf-form ref="startFormDom" :config="startFormConfig" :model="startFormData"></pf-form>
    <el-divider> 业务信息 </el-divider>
    <pf-form ref="bizFormDom" :config="bizFormConfig" :model="bizFormData"></pf-form>
    <el-divider>审批意见</el-divider>
    <pf-form
      ref="formDom"
      :config="formConfig"
      :model="formData"
      @changeEvent="formChange"
    ></pf-form>
    <el-button type="primary" @click="doCommit">提交</el-button>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, Ref, ref, toRefs } from 'vue';
import { emptyForm, FormModel, ResponseCodeEnum, useData, useHttpClient } from 'pf-component';
import { camundaApi } from '@/constants/api/camunda-api';
import { useNotice } from '@/components/element-plus/notice';
import { buildApprovalForm } from '@/views/page-config/flow/todos/form-data';

export default defineComponent({
  name: 'FlowApprovalInfo',
  props: ['processInstId', 'taskInsId', 'taskFormKey', 'startFormKey', 'taskDefinitionKey'],
  emits: ['commitDone'],
  setup(props, { emit }) {
    const _processInstId: Ref<string> = toRefs(props).processInstId;
    const _taskInsId: Ref<string> = toRefs(props).taskInsId;
    const _taskDefinitionKey: Ref<string> = toRefs(props).taskDefinitionKey;
    const formDom: Ref = ref(null);
    const formData: Ref = ref({});
    const formConfig: Ref<FormModel> = ref(buildApprovalForm());
    const startFormDom: Ref = ref(null);
    const startFormData: Ref = ref({});
    const startFormConfig: Ref<FormModel> = ref(emptyForm);
    const bizFormDom: Ref = ref(null);
    const bizFormData: Ref = ref({});
    const bizFormConfig: Ref<FormModel> = ref(emptyForm);
    const doCommit = async () => {
      const validateStatus = await formDom.value?.formRef.validate();
      if (!validateStatus) {
        useNotice().message.error('请完善信息');
        return;
      }
      const loading = useNotice().loading;
      loading.open();
      if (formData.value.opType === 'commit') {
        useHttpClient()
          .general(camundaApi.processTaskApi.commit, undefined, {
            taskId: _taskInsId.value,
            instanceId: _processInstId.value,
            comment: formData.value.comment,
            formData: { ...bizFormData.value }
          })
          .then(res => {
            if (ResponseCodeEnum.SUCCESS === res.code) {
              useNotice().message.success(res.message);
              emit('commitDone', true);
            } else {
              useNotice().message.error(res.message);
            }
          })
          .finally(() => {
            loading.close();
          });
      } else if (formData.value.opType === 'reject') {
        useHttpClient()
          .general(camundaApi.processTaskApi.reject, undefined, {
            taskId: _taskInsId.value,
            instanceId: _processInstId.value,
            taskDefinitionKey: formData.value.taskDefinitionKey,
            comment: formData.value.comment
          })
          .then(res => {
            if (ResponseCodeEnum.SUCCESS === res.code) {
              useNotice().message.success(res.message);
              emit('commitDone', true);
            } else {
              useNotice().message.error(res.message);
            }
          })
          .finally(() => {
            loading.close();
          });
      } else if (formData.value.opType === 'trans') {
        useHttpClient()
          .general(camundaApi.processTaskApi.trans, undefined, {
            taskId: _taskInsId.value,
            userId: formData.value.userId,
            comment: formData.value.comment
          })
          .then(res => {
            if (ResponseCodeEnum.SUCCESS === res.code) {
              useNotice().message.success(res.message);
              emit('commitDone', true);
            } else {
              useNotice().message.error(res.message);
            }
          })
          .finally(() => {
            loading.close();
          });
      } else {
        loading.close();
      }
    };
    const formChange = (newV: string, prop: string) => {
      if (prop === 'opType') {
        if (newV === 'reject') {
          formConfig.value.setHiddenWithRequired('userId', true, false);
          formConfig.value.setHiddenWithRequired('taskDefinitionKey', false, true);
        } else if (newV === 'commit') {
          formConfig.value.setHiddenWithRequired('userId', true, false);
          formConfig.value.setHiddenWithRequired('taskDefinitionKey', true, false);
        } else if (newV === 'trans') {
          formConfig.value.setHiddenWithRequired('userId', false, true);
          formConfig.value.setHiddenWithRequired('taskDefinitionKey', true, false);
        }
      }
    };
    const initFormConfig = () => {
      const forms = [];
      props.startFormKey &&
        forms.push({ name: props.startFormKey, config: startFormConfig, info: startFormData });
      props.taskFormKey &&
        forms.push({ name: props.taskFormKey, config: bizFormConfig, info: bizFormData });
      forms.length &&
        useData()
          .loadForm(forms)
          .then(res => {
            startFormConfig.value.disabled = true;
            useHttpClient()
              .general(camundaApi.processFormApi.startFormData, {
                processInstId: _processInstId.value
              })
              .then(res => {
                if (res.code === ResponseCodeEnum.SUCCESS) {
                  startFormData.value = res.data;
                } else {
                  useNotice().message.error('获取发单信息失败！');
                }
              });
          });
    };
    onMounted(() => {
      useHttpClient()
        .general<any[]>(camundaApi.processTaskApi.queryDoneTaskForProcess, {
          procInstId: _processInstId.value
        })
        .then(res => {
          if (ResponseCodeEnum.SUCCESS === res.code) {
            if (res.data && res.data.length > 0) {
              const map = new Map();
              res.data.forEach((v: any) => {
                // 不能驳回到=》当前激活的节点
                if (v.taskDefinitionKey !== _taskDefinitionKey.value) {
                  map.set(v.taskDefinitionKey, v.taskName);
                }
              });
              const ops: any[] = [];
              map.forEach((value, key, map1) => {
                ops.push({ key, value });
              });
              formConfig.value.setOptions('taskDefinitionKey', ops);
            }
          } else {
            useNotice().message.error(res.message);
          }
        });
    });
    return {
      formData,
      formConfig,
      formChange,
      formDom,
      doCommit,
      startFormConfig,
      startFormData,
      startFormDom,
      bizFormConfig,
      bizFormData,
      bizFormDom,
      initFormConfig
    };
  }
});
</script>
<style scoped lang="scss">
.#{$prefix} {
  &-flow-approval-info {
    //margin: 10px;
    //padding: 0;
    //overflow-y: auto;
    height: 100%;
  }
}
</style>
